<template>
  <div class="Login">
    <v-app-bar color="deep-purple accent-4" dense dark>
      <v-btn icon @click="$router.push('/')">
        <v-icon>mdi-chevron-left</v-icon>
      </v-btn>
      <v-toolbar-title>{{id?'修改信息':'注册'}}</v-toolbar-title>
    </v-app-bar>
    <div>
      <v-img
        class="mx-auto mt-4"
        width="100px"
        src="https://cdn.vuetifyjs.com/images/logos/vuetify-logo-dark.png"
        contain
      ></v-img>
      <v-form ref="form" v-model="valid" lazy-validation class="px-3">
        <v-text-field v-model="user.tel" :rules="phoneRules" label="手机号码" required :disabled="id>0"></v-text-field>
        <v-text-field v-model="user.password" :rules="pwdRules" label="密码" required></v-text-field>
        <v-text-field v-model="user.display.name" label="昵称" required></v-text-field>
        <v-text-field v-model="user.name" label="真实姓名" required></v-text-field>
        <van-field
          readonly
          clickable
          style="border-bottom:1px solid #ccc "
          label="小区"
          :value="addr"
          placeholder="选择小区"
          @click="showPicker = true"
        />
        <v-text-field v-model="addr2" label="详细地址" :rules="addressRules" required></v-text-field>
        <van-popup v-model="showPicker" position="bottom">
          <van-picker
            show-toolbar
            :columns="addrs"
            @cancel="showPicker = false"
            @confirm="onConfirm"
          />
        </van-popup>
        <v-btn
          rounded
          block
          :disabled="snackbar"
          color="success"
          class="mr-4"
          @click="validate"
        >{{id?'确认修改':'注册'}}</v-btn>
      </v-form>
      <div
        v-if="!id"
        @click="$router.push('/login')"
        style="font-size:14px;color:#41b883"
        class="text-center my-4"
      >已有账号？去登陆</div>
    </div>
  </div>
</template>
<script>
import { Notify } from "vant";
export default {
  data: () => ({
    valid: true,
    snackbar: false,
    nameRules: [
      v => !!v || "请输入用户名",
      v => (v && v.length >= 4) || "请输入4位以上的英文字母数字组合的用户名"
    ],
    pwdRules: [
      v => !!v || "请输入密码",
      v =>
        (v && v.length >= 8) ||
        "请输入8位以上的密码（英文字母数字特殊符号的组合）"
    ],
    phoneRules: [
      v => !!v || "请输入手机号码",
      v => (v && v.length == 11) || "请输入正确的11位号码"
    ],
    addressRules: [v => !!v || "请输入详细地址"],
    showPicker: false,
    addrs: [],
    addr: "",
    addr2: "",
    user: {
      useTime: 1582116835,
      CNY: 246,
      point: 963,
      type: 1,
      uID: 0,
      ID: 35,
      ask: 0,
      display: { name: "测试" },
      itemTypeCid: 0,
      name: "开发",
      other: "0",
      recv: [{ name: "开发", tel: "13619780409", address: "尚水阳光小区 2号" }],
      state: 1,
      tel: "13619780409",
      username: "13619780409"
    },
    id: false
  }),

  methods: {
    onConfirm(value) {
      this.addr = value;
      this.showPicker = false;
    },
    validate() {
      if (!this.addr) {
        Notify({ type: "warning", message: "请选择小区" });
        return;
      }
      if (this.$refs.form.validate()) {
        this.snackbar = true;
        const dData = {
          cmd: this.id ? 1 : 2,
          val: this.user
        };
        dData.val.recv[0] = {
          name: dData.val.name,
          tel: dData.val.tel,
          address: this.addr + " " + this.addr2
        };
        dData.val.table = "users";
        if (this.id) {
          dData.val.token = localStorage.token;
          dData.val.ID = this.id;
        } else {
          dData.val.username = this.tel;
          dData.val.tel = this.tel;
        }
        this.$axios.post("q.php", dData).then(res => {
          if (res.data.result) {
            Notify({
              type: "success",
              message: this.id ? "修改成功" : "注册成功"
            });
            localStorage.setItem("token", res.data.result.token);
            localStorage.setItem("name", this.user.tel);

            this.$router.push("/");
          } else {
            Notify({
              type: "warning",
              message: this.id
                ? "修改失败!服务器繁忙或登录失效,请稍后再试"
                : "注册失败,该手机号已被注册"
            });
          }
        });
      }
    }
  },
  created() {
    this.id = this.$route.params.id ? true : false;
    this.$axios
      .post("q.php", {
        cmd: 0,
        val: {
          table: "address"
        }
      })
      .then(res => {
        if (res.data.result) {
          this.addrs = res.data.result.map(a => {
            return a.name;
          });
        }
      });
    if (localStorage.token && this.id)
      this.$axios
        .post("q.php", {
          cmd: 0,
          val: { token: localStorage.token, table: "users" }
        })
        .then(res => {
          if (res.data.result) {
            this.user = this.$del(res.data.result[0], [
              "ID",
              "createTime",
              "changeTime",
              "useTime",
              "username",
              "CNY",
              "point",
              "uID",
              "state",
              "type",
              "ask"
            ]);
            this.id = res.data.result[0].ID;
            const address = res.data.result[0].recv[0].address;
            const l = address.indexOf(" ");
            this.addr = address.substr(0, l);
            this.addr2 = address.substr(l + 1);
            // console.log(this.$cp(this.user));
          } else {
            Notify({
              type: "warning",
              message: "登录超时!或服务器繁忙!请重新登录."
            });
          }
        });
  }
};
</script>